<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
<el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['mapp:windowset:add']">{{ $t('common.add') }}</el-button></el-col>
<el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['mapp:windowset:edit']">{{ $t('common.edit') }}</el-button></el-col>
<el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['mapp:windowset:remove']">{{ $t('common.delete') }}</el-button></el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/></el-row>
    <el-table v-loading="loading" :data="mtpList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('common.number')" align="center" prop="id"/>
      <el-table-column :label="$t('iot.project')" align="center" prop="projectname" width="155" show-overflow-tooltip/>
      <el-table-column :label="$t('windowset.typeid')" align="center" prop="typeid" width="99"/>
      <el-table-column :label="$t('windowset.typeName')" prop="typeid" align="center" width="139">
        <template slot-scope="scope">
          <dict-tag :options="translatedDictOptions" :value="scope.row.typeid"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('windowset.zoom')" align="center" prop="zoom" />
      <el-table-column :label="$t('windowset.lat')" align="center" prop="lat" />
      <el-table-column :label="$t('windowset.lng')" align="center" prop="lng" />
      <el-table-column :label="$t('common.operation')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['mapp:windowset:edit']">{{ $t('common.edit') }}</el-button>
<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['mapp:windowset:remove']">{{ $t('common.delete') }}</el-button>
        </template></el-table-column></el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="102px">
        <el-form-item :label="$t('iot.projectName')" prop="projectId">
          <el-select v-model="form.projectId" :placeholder="$t('iot.selectProjectName')" filterable style="width:100%" @change="handleProjectnameChange">
            <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('windowset.scenicSpotCategory')" prop="typeid">
          <el-select v-model="form.typeid" :placeholder="$t('windowset.selectScenicSpotCategory')" filterable style="width:100%">
            <el-option v-for="dict in translatedDictOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('windowset.zoom')" prop="zoom">
          <el-input-number v-model="form.zoom" :placeholder="$t('windowset.enterZoom')" :min="1" :max="5"/>
        </el-form-item>
        <el-form-item :label="$t('windowset.lat')" prop="lat">
          <el-input v-model="form.lat" :placeholder="$t('windowset.enterLat')" />
        </el-form-item>
        <el-form-item :label="$t('windowset.lng')" prop="lng">
          <el-input v-model="form.lng" :placeholder="$t('windowset.enterLng')" />
        </el-form-item></el-form>
<div slot="footer" class="dialog-footer"><el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button><el-button @click="cancel">{{ $t('common.cancel') }}</el-button></div></el-dialog></div></template>
<script>
import { listMtp, getMtp, delMtp, addMtp, updateMtp } from "@/api/iot/mtp";
import { listProject } from '@/api/iot/faproject'
export default {
  dicts:['mark_typee'],
  name: "Mtp",
  data() {
    return {
      projectnameOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 窗口设置表格数据
      mtpList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeid: null,
        projectid: null,
        zoom: null,
        lat: null,
        lng: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [{ required: true, message: this.$t('iot.projectNameRequired'), trigger: "blur" }],
      }
    };
  },
  computed: {
    currentLanguage() {
      return this.$store.getters.language || 'zh'
    },
    // 计算属性：翻译后的字典选项
    translatedDictOptions() {
      if (!this.dict || !this.dict.type || !this.dict.type.mark_typee) {
        return []
      }
      return this.dict.type.mark_typee.map(dict => ({
        ...dict,
        label: this.getTranslatedTitle(dict)
      }))
    }
  },
  watch: {
    // 监听语言变化，重新渲染组件
    currentLanguage() {
      this.$forceUpdate()
    }
  },
  created() {
    this.getList();
    this.fetchProjectnames();
  },
  methods: {
    async fetchProjectnames() {
      try {
        const response = await listProject();
        var resList=response.rows;
        if (response && resList) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            projectname: item.projectname,  // 用于展示的项目名称
          }));
          console.log("proj", this.projectnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    handleProjectnameChange(selectedId) {
      const selectedOption = this.projectnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        this.form.projectId = selectedOption.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    /** 查询窗口设置列表 */
    getList() {
      this.loading = true;
      listMtp(this.queryParams).then(response => {
        this.mtpList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        typeid: null,
        projectid: null,
        zoom: 1,
        lat: null,
        lng: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('windowset.addWindowSet');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMtp(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('windowset.editWindowSet');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMtp(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addMtp(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        this.$t('windowset.confirmDeleteWindowSet', { ids: ids }),
        this.$t('navbar.tip'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        return delMtp(ids);
      }).then(() => {
        this.getList();
        this.$message({
          type: 'success',
          message: this.$t('common.deleteSuccess')
        });
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/mtp/export', {
        ...this.queryParams
      }, `mtp_${new Date().getTime()}.xlsx`)
    },
    getTranslatedTitle(dict) {
      if (!dict || !dict.label) {
        return ''
      }
      const title = dict.label
      const chinesePattern = /[\u4e00-\u9fa5]/
      // 如果标题不包含中文字符，说明已经是翻译后的，直接返回
      if (!chinesePattern.test(title)) {
        return title
      }
      try {
        // 使用我们之前定义的菜单映射进行翻译
        const menuKeyMap = {
          '全部': 'system.allMark',
          '景点': 'system.markPoint',
          '出入口': 'system.inOut',
          '便利店': 'system.shops',
          '餐厅': 'system.eats',
          '服务': 'system.service',
          '洗手间': 'system.tolet',
          '停车场': 'system.parts',
        }
        const key = menuKeyMap[title]
        if (key && this.$t) {
          const translated = this.$t(key)
          if (translated !== key) {
            return translated
          }
        }
      } catch (error) {
        console.warn('error:', error)
      }
      return title
    }
  }
};
</script>
